package model;

import java.util.*;

@SuppressWarnings("serial")
public class Pile extends Stack<Card> {
	
	private int id;
	private int initialHashCode;
	
	public Pile(int id) {
		this.id = id;
		initialHashCode = super.hashCode();
	}
	
	public int getPileId() {
		return id;
	}
	
	public List<Card> pop(int n) {
		//System.out.println("kuku");
		List<Card> topCards = new ArrayList<Card>();
		for (int i=0; i<n; i++) {
			topCards.add(pop());
		}
		if (isValidSeq(topCards)) {
			//System.out.println("Sequence to pop() - ok");
			return reverse(topCards);
		} else {
			System.out.println("Sequence to pop() - nok");
			pushInternal(reverse(topCards));
			return null;
		}
	}
	
	private List<Card> reverse(List<Card> cards) {		
		List<Card> reversed = new ArrayList<Card>();
		Object[] c = cards.toArray();
		//System.out.println("--> Received: "+c.length);
		for (int i=c.length-1; i>=0; i--) {
			Card card = (Card) c[i];
			reversed.add(card);
		}		
		//System.out.println("--> Sent: "+reversed);
		return reversed;
	}
	
	private boolean isValidSeq(List<Card> cards) {		
		//System.out.println("Poped List: "+ cards);
		Object[] c = cards.toArray();
		
		for (int i=c.length-1; i>0; i--) {
			
			Card topCard = (Card) c[i];
			Card downCard = (Card) c[i-1];
			
			//System.out.println(topCard+" "+downCard+" "+topCard.isNext(downCard));
			if (!topCard.isNext(downCard)) {
				return false;
			}
		}
		return true;
	}
	
	public boolean push(List<Card> cards) {
		//System.out.println("Head to push:"+cards.get(0));
		if (push(cards.get(0))!=null) {
			pop();
			pushInternal(cards);
			return true;
		}
		
		return false;
	}
	
	public Card push(Card card) {
		if (	empty()	||	(peek().isNext(card))	) {
			pushInternal(card);
			return card;
		} else { return null; }
	}
	
	public void pushInternal(Card card) {
		super.push(card);
	}
	
	public void pushInternal(List<Card> cards) {
		for (Card card : cards) {
			pushInternal(card);
		}
	}
	
	public boolean equals(Object o) {
		//System.out.println("comparing");
		return (o instanceof Pile) 
			&& (((Pile)o).getPileId()==id);
		
	}
	
	public int hashCode() {
		return initialHashCode;
	}
	
	public String toString() {				
		StringBuffer s = new StringBuffer();
		s.append(id); s.append(": ");
		Object[] cards = this.toArray(); 
		for (int i=0; i<cards.length; i++) {
			s.append(cards[i].toString());
			s.append(" ");
		}
		return s.toString();
	}
}
